package com.jhz.speedy.component.control;

import android.app.Activity;

import java.util.Stack;

/**
 * 页面管理
 * Created by JunHeZ on 2017/7/13.
 */
public class ActivityManage {
    private static ActivityManage activityManage;

    private Stack<Activity> stack;  // 页面集合

    private Activity currentActivity;   // 当前的页面

    private ActivityManage(){
        stack = new Stack<>();
    }

    public static ActivityManage getInstance(){
        if(activityManage == null)
            activityManage = new ActivityManage();

        return activityManage;
    }

    /**
     * 设置当前页面
     */
    public void setCurrentActivity(Activity activity){
        currentActivity = activity;
    }

    /**
     * @return  当前页面
     */
    public Activity getCurrentActivity(){
        return currentActivity;
    }

    /**
     * 添加
     */
    public void add(Activity activity){
        stack.add(activity);
    }

    /**
     * 移除
     */
    public void remove(Activity activity){
        if(activity.equals(currentActivity)){
            currentActivity = null;
        }

        if(! activity.isFinishing()){
            activity.finish();
        }
        stack.remove(activity);
    }

    /**
     * 清除页面
     */
    public void clear(){
        currentActivity = null;

        // 遍历关闭页面
        for (int i = 0; i < stack.size(); i++){
            stack.get(i).finish();
        }

        stack.clear();
    }

    /**
     * 清除这个页面以外的其他页面
     */
    public void clearOther(Activity holdActivity){
        currentActivity = null;

        Activity act;
        // 遍历关闭页面
        for (int i = 0; i < stack.size(); i++){
            act = stack.get(i);
            if(! holdActivity.equals(act)){
                act.finish();
            }
        }
        stack.clear();
        add(holdActivity);
    }
}
